import React, { Fragment, RefObject, useEffect, useState, useMemo, useRef ,FC} from 'react'
import { request, useRequest, setPageNavBar, useLocation, Link } from 'alita'
import {  DotLoading, SearchBar, Stepper, NoticeBar, Popup, CheckList, Picker,Tag, Result, Form, Input, Button, Dialog, Checkbox, TextArea, DatePicker, CascadePicker, Selector, Slider, Switch, Cascader, Space, SideBar } from 'antd-mobile'
import type { PickerActions, PickerColumn, PickerColumnItem } from 'antd-mobile/es/components/picker'

import type { SearchBarRef } from 'antd-mobile/es/components/search-bar';
import { ACCESSTOKEN } from '@/utils/authorize';
import { getRequestInit, urlPrefix } from '@/utils/http';
import type { DetailResult , StandardNode } from '@/pages/types/type';
import styles from './index.less'

const RootStandardNodeSelector = ({ value, onChange, popupVisible, setPopupVisible }: { value?: undefined | StandardNode, popupVisible: boolean, onChange?: (val: undefined | StandardNode) => void | undefined, setPopupVisible: (x: boolean) => void }) => {
    const [nodes, setNodes] = useState<StandardNode[]>([])
    const [searchText, setSearchText] = useState<string>('')
    const [loading,setLoading] = useState<boolean>(true)

    const [searching, setSearching] = useState<boolean | undefined>(false);
    const searchRef = useRef<SearchBarRef>(null);

    function load(){
        setLoading(true);
        request('/api/standard-node-rel/get-roots', {  headers: { 'Authorization': `Bearer ${localStorage.getItem(ACCESSTOKEN)}` }, method: 'get'
        }
        ).then(({ data, code, msg }: DetailResult<StandardNode[]>) => {
            setNodes(code === 0 && data ? data.filter(n=>n.name.startsWith('0') || n.name.startsWith('1')) : [])
            if(code !==0){
                console.error(msg);
            }
            setLoading(false);
        })
    }
    useEffect(load,[]);

    return (
        <React.Fragment>
            {value ? <>{value.label}</> : `请选择作业模板`}
            <Popup
                visible={popupVisible}
                onMaskClick={() => { setPopupVisible(false) }}
                destroyOnClose
                bodyStyle={{ height: '50vh' }}
            >
                <div className={styles.searchBarContainer}>
                    <SearchBar placeholder='输入模板名称搜索' ref={searchRef}
                        value={searchText}
                        onChange={v => { setSearchText(v) }}
                        //onSearch={search}
                    />
                </div>
                {searching && <DotLoading />}
                {loading &&  <DotLoading />}
                {!loading && <div className={styles.checkListContainer}>
                    <CheckList
                        className={styles.myCheckList}
                        multiple={false}
                        defaultValue={value ? [value.sid] : []}
                        onChange={ids => {
                            onChange?.(nodes.filter(w => w.sid === ids[0])[0])
                            setPopupVisible(false)
                        }}
                    >{nodes.filter(({label})=> searchText ==='' || label.indexOf(searchText)>=0).map(({ sid, label }) => (
                        <CheckList.Item key={sid} value={sid}>
                            {label}
                        </CheckList.Item>
                    ))}
                    </CheckList>
                </div>}
                
            </Popup>
        </React.Fragment>
    )
}

const RootStandardNodePicker :FC<{ name: string, required: boolean, label: string }> =({ name,required,label })=>{
    const [loading, setLoading] = useState<boolean>(true);
    const [loadFail, setLoadFail] = useState<string | undefined>(undefined);
    const [loadSuccess, setLoadSuccess] = useState<string | undefined>(undefined);
    const [weiXinUsers, setWeiXinUsers] = useState<PickerColumn[]>([])
    function load() {
        setLoading(true);
        setLoadFail(undefined);
        setLoadSuccess(undefined);
        let response: Promise<Response> = fetch(`${urlPrefix}/api/standard-node-rel/get-roots`, getRequestInit())
        response.then((rsp: Response) => {
            console.log(rsp);
            if (rsp.ok) {
                rsp.json().then(async ({ data, code, msg }: DetailResult<StandardNode[]>) => {
                    if (code === 0) {
                        setWeiXinUsers([data!.map(u => {
                            const x: PickerColumnItem = { label: u.label , value: u.value, key: u.value }
                            return x;
                        }),])
                        setLoadSuccess(msg);
                    } else {
                        setLoadFail(msg);
                    }
                }).catch(reason => {
                    setLoadFail(reason);
                })
            }
        }).catch((reason: any) => {
            console.error(reason);
            setLoadFail(`发生错误：${reason}`)
        }).finally(() => {
            setLoading(false);
        })
    }
    useEffect(load, []);

    return <Form.Item name={name} label={label} rules={[{ required, message: label }]}
        trigger='onConfirm'
        onClick={(e, pickRef: RefObject<PickerActions>) => {
            pickRef.current?.open()
        }}
    >
        <Picker columns={weiXinUsers}>
            {value =>value.length >0? value[0]?.label :'' }
        </Picker>
    </Form.Item>
}

export {RootStandardNodeSelector, RootStandardNodePicker};

